package cn.org.custom.server;

import cn.org.custom.protocol.ProcotolFrameDecoder;
import cn.org.custom.utils.CloseTool;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import static cn.org.custom.server.constants.Constants.*;


@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();// 生产线对象
                    pipeline.addLast(new ProcotolFrameDecoder());
//                    pipeline.addLast(LOGGING_HANDLER);
                    pipeline.addLast(MESSAGE_CODEC);
                    /**
                     * 心跳
                     */
                    pipeline.addLast(IDLE_STATE_HANDLER);
                    pipeline.addLast(HEART_BEAT_HANDLER);
                    /**
                     * 自定义业务处理器
                     */
                    pipeline.addLast(LOGIN_HANDLER);
                    pipeline.addLast(CHAT_HANDLER);
                    pipeline.addLast(GROUP_CREATE_HANDLER);
                    pipeline.addLast(GROUP_JOIN_HANDLER);
                    pipeline.addLast(GROUP_MEMBERS_HANDLER);
                    pipeline.addLast(GROUP_QUIT_HANDLER);
                    pipeline.addLast(GROUP_CHAT_HANDLER);
                    pipeline.addLast(QUIT_HANDLER);
                    pipeline.addLast(PING_MESSAGE_HANDLER);
                }
            });
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            log.info("----------服务器启动成功---------");
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            CloseTool.closeEventLoopGroup(boss, worker);
        }
    }
}
